import React,{useEffect} from 'react';
import RNBootSplash from "react-native-bootsplash";
import {NavigationContainer, useFocusEffect} from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import {
    Alert,
    BackHandler,
    Image,
    SafeAreaView,
    StyleSheet,
    ToastAndroid,
    TouchableWithoutFeedback,
    View
} from "react-native";
import AsyncStorage from '@react-native-async-storage/async-storage';
import {
    Button,
    Card,
    Divider,
    Icon,
    Input,
    Layout,
    Text,
    TopNavigation,
    TopNavigationAction
} from "@ui-kitten/components";
import {ServicingTicketScreen} from './Screens/ServicingTicketScreen'
import {AddTicketCollectionScreen} from "./Screens/AddTicketCollectionScreen";
import {AddTicketSuccessScreen} from "./Screens/AddTicketSuccessScreen";
import {ReceiveLiveItemsScreen} from "./Screens/ReceiveLiveItemsScreen";
import {RepairCompletScreen} from "./Screens/RepairCompletScreen";
import {ItemTestScreen} from "./Screens/ItemTestScreen";
import {FixEndScreen} from  "./Screens/FixEndScreen";
import {SelectFixItemScreen} from "./Screens/SelectFixItemScreen";
import {ScpoeCheckScreen} from  "./Screens/ScpoeCheckScreen";
import SorageManager from "./Compoments/SorageManager";
import {showMessage} from "react-native/Libraries/Utilities/LoadingView";

/**
 * 顶部返回按钮
 * @param props
 * @returns {JSX.Element}
 * @constructor
 */
const BackIcon = (props) => (
    <Icon {...props} name='arrow-back' />
);

/**
 * 设置请求参数
 * @type {{redirect: string, method: string}}
 */
const requestOptions = {
    method: 'GET',
    redirect: 'follow'
};


const { Navigator, Screen } = createStackNavigator();


const getData = async (k) => {
    try {
        const jsonValue = await AsyncStorage.getItem(k)
        return jsonValue != null ? JSON.parse(jsonValue) : null;
    } catch(e) {
    }
}

/**
 * 登陆页面
 * @param navigation
 * @returns {JSX.Element}
 * @constructor
 */
const LoginScreen = ({ navigation }) => {
    const [userInf, setUserInf] = React.useState('');
    const getData = async () => {
        try {
            const jsonValue = await AsyncStorage.getItem('userInf')
            return jsonValue != null ? JSON.parse(jsonValue) : null;
        } catch(e) {
           ToastAndroid.show("请开放本地存储权限")
        }
    }


    useEffect(() => {
        const init = async () => {
            // …do multiple sync or async tasks
        };

        init().finally(async () => {
            await RNBootSplash.hide({ fade: true });
            console.log("Bootsplash has been hidden successfully");
        });

            //自动登陆
        // getData().then(userInf=>{
        //     if (userInf!= null){
        //         navigation.navigate('Menu');
        //         showToast("自动登陆成功")
        //     }
        // })


        SorageManager.get('userInf').then(r =>{
            console.log(r,"userINF")
            getPromisList(r["userid"])
        } )


    }, []);

    const showToast = (message) => {
        ToastAndroid.show(message, ToastAndroid.SHORT);
    };




    const saveLocalStorage = async (k,v)=>{
        try {
            const jsonValue = JSON.stringify(v)
            await AsyncStorage.setItem(k, jsonValue)
            // showToast("登陆成功")
            navigation.navigate('Menu');
        } catch (e) {
            // saving error
            console.log(e)
            showToast("请给予本地存储权限")
        }
        // try{
        //     await AsyncStorage.setItem('userInf',v)
        //     console.log("存储用户信息完成")
        //     showToast("登陆成功")
        //     navigation.navigate('Menu');
        // }catch (e){
        //     showToast(e)
        // }
    }

    /**
     * 获取权限列表
     * @param userid
     */
    const getPromisList=(userid)=>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };

        fetch("http://htjoa.nrnet.cn/dc14/jwmis/state/state?userid="+userid, requestOptions)
            .then(response => response.json())
            .then(result =>{
                saveLocalStorage('hxjy',"no")
                saveLocalStorage('hxlq',"no")
                saveLocalStorage('sxjs',"no")
                saveLocalStorage('zbjs',"no")
                saveLocalStorage('zbtp',"no")
                console.log(result,"获取权限列表")
                result.map((item,index)=>{
                    console.log(item)
                   if(item["name"]==="活项检验"){
                       saveLocalStorage("hxjy","yes")
                   }
                    if(item["name"]==="活项领取"){
                        saveLocalStorage("hxlq","yes")
                    }
                    if(item["name"]==="施修结束"){
                        saveLocalStorage("sxjs","yes")
                    }
                    if(item["name"]==="整备结束"){
                        saveLocalStorage("zbjs","yes")
                    }
                    if(item["name"]==="整备提票"){
                        saveLocalStorage("zbtp","yes")
                    }
                })

            })
            .catch(error => console.log('error', error));
    }

    /**
     * 检查登陆是否成功
     * @param userID
     * @param password
     */
    const checkLogin=(userID,password)=>{
        fetch("http://htjoa.nrnet.cn/dc14/jwmis/user/user?userid="+userID+"&password="+password, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result);
                if(result["code"]==="200"){
                  saveLocalStorage("userInf",result)
                }else {
                    showToast("检查用户名和密码")
                }
            })
            .catch(error => {
                console.log('error', error)
                showToast("请检查网络")
            });

    }


    const navigateMenu = () => {
       checkLogin(userID,password);
    };




    const AlertIcon = (props) => (
        <Icon {...props} name='alert-circle-outline'/>
    );

        const [secureTextEntry, setSecureTextEntry] = React.useState(true);

        const toggleSecureEntry = () => {
            setSecureTextEntry(!secureTextEntry);
        };

        const renderIcon = (props) => (
            <TouchableWithoutFeedback onPress={toggleSecureEntry}>
                <Icon {...props} name={secureTextEntry ? 'eye-off' : 'eye'}/>
            </TouchableWithoutFeedback>
        );

        const renderCaption = () => {
            return (
                <View style={styles.captionContainer}>
                    {AlertIcon(styles.captionIcon)}
                    <Text style={styles.captionText}>Should contain at least 8 symbols</Text>
                </View>
            )
        }



        const [password, setPassword] = React.useState('');
    const [userID, setUserID] = React.useState('');
    return (
        <SafeAreaView style={{ flex: 1 }}>
            <TopNavigation title='登陆' alignment='center'/>
            <Divider/>
            <Layout style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>

                <Image source={require('./huoche.png')}  style={{width:90,height:90}}>

                </Image>

                <Text style={{fontSize:40,marginBottom:40}}>
                    机务整备系统
                    <Text >
                    V1.0
                </Text>
                </Text>


                <Layout style={{marginLeft:5,marginRight:5,marginBottom:40,width:300}}>
                    <Input
                        label='用户名：'
                        placeholder='请输入用户名'
                        value={userID}
                        onChangeText={nextValue => setUserID(nextValue)}
                    />


                    <Input
                        label='密码：'
                        placeholder='请输入密码'
                        value={password}
                        onChangeText={nextValue => setPassword(nextValue)}






                        accessoryRight={renderIcon}
                        secureTextEntry={secureTextEntry}
                    />
                </Layout>


                {/*<Input*/}
                {/*    placeholder='Place your Text'*/}
                {/*    value={value}*/}
                {/*    onChangeText={nextValue => setPassword(nextValue)}*/}
                {/*/>*/}
                <Button onPress={navigateMenu} style={{width:300}}>登陆</Button>
            </Layout>
        </SafeAreaView>
    );
};

/**
 * 菜单页面
 * @param navigation
 * @returns {JSX.Element}
 * @constructor
 */
export const MenuScreen = ({ navigation }) => {

    const [userInf, setUserInf] = React.useState('');


    /**
     * 获取权限列表
     * @param userid
     */
    const getPromisList=(userid)=>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };

        fetch("http://htjoa.nrnet.cn/dc14/jwmis/state/state?userid="+userid, requestOptions)
            .then(response => response.json())
            .then(result =>{
                saveLocalStorage('hxjy',"no")
                saveLocalStorage('hxlq',"no")
                saveLocalStorage('sxjs',"no")
                saveLocalStorage('zbjs',"no")
                saveLocalStorage('zbtp',"no")
                console.log(result,"获取权限列表")
                result.map((item,index)=>{
                    console.log(item)
                    if(item["name"]==="活项检验"){
                        saveLocalStorage("hxjy","yes")
                    }
                    if(item["name"]==="活项领取"){
                        saveLocalStorage("hxlq","yes")
                    }
                    if(item["name"]==="施修结束"){
                        saveLocalStorage("sxjs","yes")
                    }
                    if(item["name"]==="整备结束"){
                        saveLocalStorage("zbjs","yes")
                    }
                    if(item["name"]==="整备提票"){
                        saveLocalStorage("zbtp","yes")
                    }
                })

            })
            .catch(error => console.log('error', error));
    }


    useFocusEffect(() => {
        const backAction = () => {
            Alert.alert("退出应用", "是否要返回主屏幕", [
                {
                    text: "取消",
                    onPress: () => null,
                    style: "cancel"
                },
                { text: "退出", onPress: () => BackHandler.exitApp() }
            ]);
            return true;
        };

        const backHandler = BackHandler.addEventListener(
            "hardwareBackPress",
            backAction
        );

        return () => backHandler.remove();
    });


    const getData = async () => {
        try {
            const jsonValue = await AsyncStorage.getItem('userInf')
            return jsonValue != null ? JSON.parse(jsonValue) : null;
        } catch(e) {
            // error reading value
        }
    }



    useEffect(()=>{
        getData().then(c=>{
            setUserInf(c)})


        SorageManager.get('userInf').then(r =>{
            console.log(r,"userINF")
            getPromisList(r["userid"])
        } )



    },[])
    // useEffect(()=>{
    //     // getData().then(c=>{
    //     //     console.log(c["dutyname"])
    //     //     setUserInf(c)})
    //     getData();
    //
    // },[])

    const navigateBack = () => {
        navigation.goBack();
    };

    //整备提票
    const navigateServicingTicket = () => {

        SorageManager.get('zbtp').then(r =>{
            console.log(r,"zbtp")
            if (r === "yes"){
                navigation.navigate('ServicingTicket');
            }else {
                showMessage("暂无权限")
            }
        } )



    };

    //活项领取
    const navigateReceiveLiveItems = () => {
        SorageManager.get('hxlq').then(r =>{
            console.log(r,"hxlq")
            if (r === "yes"){
                navigation.navigate('ReceiveLiveItems');
            }else {
                showMessage("暂无权限")
            }
        } )
    };

    //活项检验
    const navigateItemTest = () => {

        SorageManager.get('hxjy').then(r =>{
            console.log(r,"hxjy")
            if (r === "yes"){
                navigation.navigate('ItemTest');
            }else {
                showMessage("暂无权限")
            }
        } )

    };

    const deleteUserInf = async () => {
        try {
            await AsyncStorage.setItem('userInf', null)
            return true
        } catch (e) {
            // saving error
            return false
        }
    }

    //施修结束
    const navigateRepairComplete = () => {

        SorageManager.get('sxjs').then(r =>{
            console.log(r,"sxjs")
            if (r === "yes"){
                navigation.navigate('RepairComplete');
            }else {
                showMessage("暂无权限")
            }
        } )
    };


    const navigateFixEnd = () => {
        SorageManager.get('zbjs').then(r =>{
            console.log(r,"zbjs")
            if (r === "yes"){
                navigation.navigate('FixEnd');
            }else {
                showMessage("暂无权限")
            }
        } )



    };

    const saveLocalStorage = async (k,v)=>{
        try {
            const jsonValue = JSON.stringify(v)
            await AsyncStorage.setItem(k, jsonValue)
            console.log("存储用户信息完成")
            // showToast("登陆成功")
            navigation.navigate('Menu');
        } catch (e) {
            // saving error
            console.log(e)
            showToast("请给予本地存储权限")
        }
        // try{
        //     await AsyncStorage.setItem('userInf',v)
        //     console.log("存储用户信息完成")
        //     showToast("登陆成功")
        //     navigation.navigate('Menu');
        // }catch (e){
        //     showToast(e)
        // }
    }

    const navigateLogin = () => {

        Alert.alert("", "退出登陆", [
                    {
                        text: "取消",
                        onPress: () => null,
                        style: "cancel"
                    },
                    {
        //                 saveLocalStorage('hxjy',"no")
        // saveLocalStorage('hxlq',"no")
        // saveLocalStorage('sxjs',"no")
        // saveLocalStorage('zbjs',"no")
        // saveLocalStorage('zbtp',"no")


                        text: "确定", onPress: () => {
                            AsyncStorage.removeItem("hxjy").then(()=>{
                                console.log("清除hxjy")
                            })
                            AsyncStorage.removeItem('hxlq').then(()=>{
                                console.log("清除hxlq")
                            })
                            AsyncStorage.removeItem('sxjs').then(()=>{
                                console.log("清除sxjs")
                            })
                            AsyncStorage.removeItem('zbjs').then(()=>{
                                console.log("清除zbjs")
                            })
                            AsyncStorage.removeItem('zbtp').then(()=>{
                                console.log("清除zbtp")
                            })
                            AsyncStorage.removeItem('userInf').then(()=>{
                                console.log("清除userInf")
                            })

                            navigation.navigate('Login')
                        } }
                ]);
    };

    const BackAction = () => (
        <TopNavigationAction icon={BackIcon} onPress={navigateBack}/>
    );



    return (
        <SafeAreaView style={{ flex: 1 }}>
            <TopNavigation title='菜单' alignment='center' />
            <Divider/>
            <Layout >

                <View style={styles.NameView}>
                    <Text style={styles.NameText}>{userInf["name"]}</Text>
                    <Button onPress={navigateLogin}  appearance='outline' status='warning'>退出登陆</Button>
                </View>

<View style={{height:'100%'}}>
                <View style={styles.MenuListContainer}>
                    <View style={styles.MenuItemColum}>
                        <Card onPress={navigateServicingTicket}
                              appearance='filled'
                        >
                            <Icon
                                // onPress={navigateServicingTicket}
                                style={{height:40}}
                                fill='#4F67B8'
                                name='book-outline'
                            />
                            <Text>
                                整备提票
                            </Text>
                        </Card>
                        <Card onPress={navigateReceiveLiveItems}
                              appearance='filled'>
                            <Icon
                                // onPress={navigateServicingTicket}
                                style={{height:40}}
                                fill='#F2956D'
                                name='book-open-outline'
                            />
                            <Text>
                                活项领取
                            </Text>
                        </Card>


                        {/*<Button onPress={() => showToast()} >*/}
                        {/*    领取活项*/}
                        {/*</Button>*/}
                    </View>

                    <View style={styles.MenuItemColum}>

                        <Card onPress={navigateRepairComplete}
                              appearance='filled'>
                            <Icon
                                // onPress={navigateServicingTicket}
                                style={{height:40}}
                                fill='#5E3A40'
                                name='flag-outline'
                            />
                            <Text>
                                施修结束
                            </Text>
                        </Card>


                        <Card onPress={navigateItemTest}
                              appearance='filled'>
                            <Icon
                                // onPress={navigateServicingTicket}
                                style={{height:40}}
                                fill='#379F7A'
                                name='checkmark-circle-outline'
                            />
                            <Text>
                                活项检验
                            </Text>
                        </Card>


                    </View>

                    <View style={styles.MenuItemColum}>

                        <Card onPress={navigateFixEnd}
                              appearance='filled'>
                            <Icon
                                // onPress={navigateServicingTicket}
                                style={{height:40}}
                                fill='#9EAA40'
                                name='layers-outline'
                            />
                            <Text>
                                范围检查
                            </Text>
                        </Card>


                        <Card
                              appearance='filled'
                        >
                            <Icon
                                // onPress={navigateServicingTicket}
                                style={{height:40,color:'rgba(0, 0, 0, 0)'}}
                                fill='rgba(0, 0, 0, 0)'
                                name='checkmark-circle-outline'
                            />
                            <Text style={{color:'rgba(0, 0, 0, 0)'}}>
                                活项检验
                            </Text>
                        </Card>


                    </View>

                </View>
</View>


            </Layout>
        </SafeAreaView>
    );
};


/**
 * app路由系统
 * @returns {JSX.Element}
 * @constructor
 */
const HomeNavigator = () => (
    <Navigator screenOptions={{headerShown: false}}>
        <Screen name='Login' component={LoginScreen}/>
        <Screen name='Menu' component={MenuScreen}/>
        <Screen name='ServicingTicket' component={ServicingTicketScreen}/>
        <Screen name='AddTicketCollection' component={AddTicketCollectionScreen}/>
        <Screen name='AddTicketSuccess' component={AddTicketSuccessScreen}/>
        <Screen name='ReceiveLiveItems' component={ReceiveLiveItemsScreen}/>
        <Screen name='RepairComplete' component={RepairCompletScreen}/>
        <Screen name='ItemTest' component={ItemTestScreen}/>
        <Screen name='FixEnd' component={FixEndScreen}/>
        <Screen name='SelectFixItem' component={SelectFixItemScreen}/>
        <Screen name='ScpoeCheck' component={ScpoeCheckScreen} />
    </Navigator>
);

/**
 * 页面路由系统
 * @returns {JSX.Element}
 * @constructor
 */
export const AppNavigator = () => (
    <NavigationContainer>
        <HomeNavigator/>
    </NavigationContainer>
);


const styles = StyleSheet.create({
    MenuListContainer: {
        minHeight:400,
        display: 'flex',
        // borderWidth:1,
        // borderColor:'#306fde',
        justifyContent:'space-evenly'
        // justifyContent: 'space-evenly'
    },
    MenuItemColum:{
        display :'flex',
        flexDirection:"row",
        alignItems: 'center',
        justifyContent:'space-evenly'
    },
    NameView:{
        marginTop:20,
        display: 'flex',
        flexDirection: "row",
        alignItems: 'center',
        justifyContent:'space-evenly'
    },
    NameText:{
        fontSize:24,
        fontWeight:'bold'
    },

    unDisplay:{
        color:'rgba(0, 0, 0, 0.0)'
    }

})